﻿using ProjectScheduling.models;
using System.Data;

namespace ProjectScheduling
{
    public partial class CheckStaffForm : Form
    {
        private readonly DataTable t_all = new();
        private readonly DataTable t_checked = new();
        public static readonly CheckStaffForm b = new();
        public Action<List<(int id, string name)>>? action;
        public void SetAllUsers(List<Users> allusers)
        {
            t_all.Clear();
            var checks = t_checked.Rows.Cast<DataRow>().Select(it => it["ID"]?.ToString());
            foreach (Users user in allusers)
            {
                var row=t_all.NewRow();
                row["ID"] = user.Id;
                row["Name"] = user.Name;
                row["Checked"]= checks.Contains(user.Id.ToString()) ? "1" : "0";
            }
            
            view_all.DataSource = t_all;
        }
        public void InitData(List<(int id, string name)> datas)
        {
            t_checked.Rows.Clear();
            datas.ForEach(item =>
            {
                var row = t_checked.NewRow();
                row["ID"] = item.id;
                row["Name"] = item.name;
                t_checked.Rows.Add(row);
            });
            view_checked.DataSource = t_checked;
            //view_checked.DataSource = t_checked;
        }
        public CheckStaffForm()
        {
            InitializeComponent();
            void _(DataTable dt, params string[] colName) => colName.ToList().ForEach(it => dt.Columns.Add(new DataColumn(it)));
            _(t_checked, "ID", "Name");
            _(t_all, "Checked", "ID", "Name");
        }
        // 显示页面的时候 列出来所有员工
        private void CheckStaffForm_Shown(object sender, EventArgs e)
        {

        }

        private void View_all_SelectionChanged(object sender, EventArgs e)
        {
            view_all.ClearSelection();
        }

        private void Txt_search_key_TextChanged(object sender, EventArgs e)
        {

            var tb2 = t_all.Copy();
            var key = txt_search_key.Text;
            var checkedIds = (view_checked.DataSource as DataTable)?.Rows.Cast<DataRow>().Select(it => it["Id"].ToString() ?? "").ToList() ?? [];
            if (!string.IsNullOrEmpty(key))
            {
                foreach (DataRow row in tb2.Rows)
                {
                    if (!(row["Name"]?.ToString() ?? "").Contains(txt_search_key.Text))
                    {
                        row.Delete();
                    }
                    else
                    {
                        row["Checked"] = checkedIds.Contains(row["Id"].ToString() ?? "") ? "1" : "0";
                    }
                }
            }
            else
            {
                foreach (DataRow row in tb2.Rows)
                {
                    row["Checked"] = checkedIds.Contains(row["Id"].ToString() ?? "") ? "1" : "0";
                }
            }
            view_all.DataSource = tb2;
        }

        private void View_all_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex != 0) return;
            var row = view_all.Rows[e.RowIndex];
            if (row == null) return;
            if (row.Cells[0] is DataGridViewCheckBoxCell ch)
            {
                (string id, string name) = (row.Cells[1].Value.ToString() ?? "", row.Cells[2].Value.ToString() ?? "");
                if ((bool)ch.EditingCellFormattedValue)
                {
                    // 添加数据到选中
                    if (!t_checked.Rows.Cast<DataRow>().Any(it => it["ID"].ToString() == id))
                    {
                        var _row = t_checked.NewRow();
                        _row["ID"] = id;
                        _row["Name"] = name;
                        t_checked.Rows.Add(_row);
                    }
                }
                else
                    // 从选中中删除
                    t_checked.Rows.Cast<DataRow>().FirstOrDefault(it => it["ID"].ToString() == id)?.Delete();
                view_checked.DataSource = t_checked;
                txt_count.Text = $"选中（{t_checked.Rows.Count}）";
            }

        }

        private void View_checked_SelectionChanged(object sender, EventArgs e)
        {
            view_checked.ClearSelection();
        }

        private void View_checked_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex != 0 || e.RowIndex == -1) return;
            string id = "";
            if (view_checked.DataSource is not DataTable dt) return;
            id = dt.Rows[e.RowIndex]["Id"].ToString() ?? "";
            if (view_all.DataSource is not DataTable dt1) return;
            var row = dt1.Rows.Cast<DataRow>().FirstOrDefault(it => it["Id"].ToString() == id);
            if (row != null)
            {
                row["Checked"] = "0";
            }
            dt.Rows[e.RowIndex].Delete();
            view_all.DataSource = dt1;
        }

        private void Btn_ok_Click(object sender, EventArgs e)
        {
            static int toInt(object o)
            {
                return Convert.ToInt32(o);
            }
            var list = (view_checked.DataSource as DataTable)?.Rows.Cast<DataRow>().Select(it => (id: toInt(it["Id"]), name: it["Name"].ToString() ?? "")).ToList();
            action?.Invoke(list ?? []);
            Close();
        }
    }
}
